package com.soup.lab.third.token;

import com.alibaba.fastjson.annotation.JSONField;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

public class Token {
    /**
     * 提前死亡时间
     * 由于在网络IO，存在延时，为了避免重试，在token死亡3分钟前更新
     */
    private static final int ADVANCE_DEAD_TIME = 3 * 60;
    /**
     * token内容
     */
    private final String content;
    /**
     * token截止时间
     * 为 -1 表示仅当次有效
     */
    private final long cutOffTime;

    public Token(String content, long cutOffTime) {
        this.content = content;
        this.cutOffTime = cutOffTime;
    }

    public static Token of(String content, int expire) {
        long cutOffTime = -1;
        if(expire > 0) {
            if(expire < ADVANCE_DEAD_TIME) {
                return new Token(content, cutOffTime);
            }
            cutOffTime = System.currentTimeMillis() + (expire - ADVANCE_DEAD_TIME) * 1000;
        }
        return new Token(content, cutOffTime);
    }

    private boolean isExpired() {
        return cutOffTime != -1 && cutOffTime < System.currentTimeMillis();
    }

    private boolean isEmpty() {
        return StringUtils.isBlank(content);
    }

    @JSONField(serialize = false)
    public boolean isValid() {
        return !isEmpty() && !isExpired();
    }

    public String getContent() {
        return content;
    }

    @JSONField(serialize = false)
    public int getExpireSeconds() {
        long expireMilliseconds = cutOffTime - System.currentTimeMillis();
        if(expireMilliseconds <= 0) {
            return -1;
        }
        return (int) TimeUnit.SECONDS.convert(expireMilliseconds, TimeUnit.MILLISECONDS);
    }

    public long getCutOffTime() {
        return cutOffTime;
    }

    @Override
    public String toString() {
        return "Token{" +
                "content='" + content + '\'' +
                ", cutOffTime=" + cutOffTime +
                '}';
    }

}
